package com.zhangbaiyan.test4;

import java.util.Random;

/**
 * @author zhangbaiyan
 * @date 2024-09-24 21:23
 * @description:
 * @version:
 */
public class MyThread extends Thread {
    //共享数据
    //100块,分成3个红包
    static int money = 100;
    static int count = 3;

    //最小的中将金额
    static final double Min = 0.1;

    @Override
    public void run() {
        //同步代码块
        synchronized (MyThread.class) {
            if (count == 0) {
                //判断,共享数据是否到了末尾(已经到了末尾)
                System.out.println(getName() + "红包已经发完");
            } else {
                //判断,共享数据是否到了末尾(没有到末尾)
                //定义一个变量,表示中奖的金额
                double prize = 0;
                if (count == 1) {
                    //表示此时是最后一个红包
                    //就无需岁机,剩余所有的钱都是中将金额
                    prize = money;
                } else {
                    //表示第一次,第二次(随机)
                    Random r = new Random();
                    //100元 3个包
                    //第一个红包:99.98
                    //100-(3-1)*0.01
                    double bounds = money - (count - 1) * Min;
                    prize = r.nextDouble(bounds);
                    if (prize < Min) {
                        prize = Min;
                    }

                }
                //从money当中,去掉当前中奖的金额
                money -= prize;
                //红包的个数-1
                count--;
                //本次红包的信息进行打印
                System.out.println(getName() + "抢到" + prize+"元");
            }
        }
    }
}

